import re
import json
import logging

import django_redis

from utils import constants
from utils.views import LoginRequiredJSONMixin
from django.contrib.auth import authenticate, login, logout
from celery_tasks.email.tasks import send_verify_email
from django.conf import settings
from django.core.mail import send_mail
from django.views import View
from .models import User, Address
from django.http import JsonResponse, HttpResponseBadRequest
from .utils import generate_verify_email_url, check_verify_email_token

logger = logging.getLogger('django')


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    """用户注册"""

    def post(self, request):
        """
        :param request: 请求对象
        :return: JSON
        """
        # 接收参数：请求体中的JSON数据 request.body
        json_dict = json.loads(request.body.decode())
        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 判断参数是否齐全
        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数!'})
        # 判断用户名是否是5 - 20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 判断手机号是否合法
        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})

        # 判断短信验证码是否正确
        # 提取服务端存储的短信验证码
        redis_conn = django_redis.get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 判断短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 保存注册数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': f'注册失败, 原因：{e}'})

        return JsonResponse({'code': 0, 'errmsg': '注册成功'})


class LoginView(View):
    """用户登录"""

    def post(self, request):
        """
        实现登录逻辑
        :param request: 请求对象
        :return: 登录结果
        """
        # 接收参数：请求体中的JSON数据 request.body
        json_dict = json.loads(request.body.decode())

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 判断参数是否齐全
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数!'})

        # 根据登录数据修改用户认证字段
        if re.match(r'^1[3-9]\d{9}$', username):
            # 手机号
            User.USERNAME_FIELD = 'mobile'
        else:
            # account 是用户名
            # 根据用户名从数据库获取 user 对象返回.
            User.USERNAME_FIELD = 'username'

        # 验证是否能够登录
        user = authenticate(username=username, password=password)

        # 判断是否为空, 如果为空, 返回
        if not user:
            return JsonResponse({'code': 400, 'errmsg': '用户名或者密码错误'})

        # 状态保持
        login(request, user)

        # 判断是否记住用户
        if not remembered:
            # 7.如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        else:
            # 6.如果记住: 设置为两周有效
            request.session.set_expiry(None)

        response = JsonResponse({'code': 0, 'errmsg': '登录成功'})
        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class LogoutView(View):
    """退出登录"""

    def delete(self, request):
        """
        实现退出登录逻辑
        :param request: 请求对象
        :return: 退出登录结果
        """
        # 清理session
        logout(request)

        # 退出登录，重定向到登录页
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    """用户信息"""

    def get(self, request):
        """
        提供个人信息界面
        :param request: 请求对象
        :return: 用户信息
        """
        is_auth = request.user.is_authenticated
        if is_auth:
            # 获取界面需要的数据,进行拼接
            info_data = {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }

            return JsonResponse({
                'code': 0,
                'errmsg': '个人中心',
                "info_data": info_data
            })
        else:
            return JsonResponse({'code': 403, 'errmsg': '用户未授权'})


class EmailsView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 赋值email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

        # 发送验证邮件
        verify_url = generate_verify_email_url(request.user)
        subject = "美多商城邮箱验证"
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p style="color: red; text-indent: 2em;">感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        try:
            result = send_mail(subject, '', settings.EMAIL_FROM, [email], html_message=html_message)
        except Exception as e:
            logger(e)

        # 响应添加邮箱结果
        return JsonResponse({'code': 0, 'errmsg': '添加邮箱成功', 'result': result})


class VerifyEmailsView(View):
    """邮箱验证"""

    def put(self, request):
        # - 1.接收 token
        token = request.GET.get('token')

        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # - 2.解密
        data_dict = check_verify_email_token(token)
        if not data_dict:
            return JsonResponse({'code': 400, 'errmsg': 'token失效'})

        # - 3.去数据库对比 user_id,email
        try:
            user = User.objects.get(pk=data_dict.get('user_id'), email=data_dict.get('email'))
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # - 4.修改激活状态
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return JsonResponse({'code': 0, 'errmsg': '激活失败!'})
        else:
            return JsonResponse({'code': 200, 'errmsg': '激活成功'})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """用户新增收货地址"""

    def post(self, request):
        """实现新增地址逻辑"""
        # 判断是否超过地址上限：最多20个
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 接收参数
        try:
            json_dict = json.loads(request.body.decode())
        except Exception as e:
            json_dict = {}

        # 提取参数
        receiver = json_dict.get('receiver')
        title = json_dict.get('title')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseBadRequest('缺少必要参数')
        # 判断手机号是否合法
        if not re.match(r'1[3-9]\d{9}', mobile):
            return HttpResponseBadRequest('mobile格式有误!')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseBadRequest('参数email有误')

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                receiver=receiver,
                title=receiver,
                mobile=mobile,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                tel=tel,
                email=email
            )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})


class AddressesView(LoginRequiredJSONMixin, View):
    """查询用户收货地址"""

    def get(self, request):
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'province_id': address.province_id,
                'city': address.city.name,
                'city_id': address.city_id,
                'district': address.district.name,
                'district_id': address.district_id,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            }
            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'addresses': address_dict_list,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'default_address_id': default_id
        })


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改用户收货地址"""

        # 接收参数
        try:
            json_dict = json.loads(request.body.decode())
        except Exception as e:
            json_dict = {}
        # 提取参数
        receiver = json_dict.get('receiver')
        title = json_dict.get('title')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile, title]):
            return HttpResponseBadRequest('缺少必要参数')
        # 判断手机号是否合法
        if not re.match(r'1[3-9]\d{9}', mobile):
            return HttpResponseBadRequest('参数mobile有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseBadRequest('参数email有误')

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(pk=address_id).update(
                user=request.user,
                receiver=receiver,
                title=title,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('更新地址失败')

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'title': address.title,
            'province': address.province.name,
            'province_id': address.province_id,
            'city': address.city.name,
            'city_id': address.city_id,
            'district': address.district.name,
            'district_id': address.district_id,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }

        return JsonResponse({'code': 0, 'errmsg': '修改地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除用户收货地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(pk=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})
        # 响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """修改地址标题"""

    def put(self, request, address_id):
        # 接收参数
        try:
            json_dict = json.loads(request.body.decode())
        except Exception as e:
            json_dict = {}
        # 提取参数
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        return JsonResponse({'code': 0, 'errmsg': '修改地址别名成功'})


class UpdatePasswordView(LoginRequiredJSONMixin, View):
    """修改密码"""

    def put(self, request):
        # 接收参数
        try:
            json_dict = json.loads(request.body.decode())
        except Exception as e:
            json_dict = {}
        # 提取参数
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入不一致!'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': '修改密码成功！'})
        response.delete_cookie('username')

        # 响应密码修改结果：重定向到登录界面
        return response
